package com.bigfans.searchservice.api.clients;

import com.bigfans.api.clients.ServiceRequest;
import com.bigfans.framework.utils.BeanUtils;
import com.bigfans.searchservice.SearchApplications;
import com.bigfans.searchservice.model.Order;
import com.bigfans.searchservice.model.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class OrderServiceClient {

    @Autowired
    private RestTemplate restTemplate;

    public CompletableFuture<Order> getOrder(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            ServiceRequest serviceRequest = new ServiceRequest(restTemplate, SearchApplications.getFunctionalUser());
            Map data = serviceRequest.get(Map.class, "http://order-service/orders/{orderId}", orderId);
            Order category = BeanUtils.mapToModel(data, Order.class);
            return category;
        });
    }

    public CompletableFuture<List<OrderItem>> getOrderItems(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            ServiceRequest serviceRequest = new ServiceRequest(restTemplate, SearchApplications.getFunctionalUser());
            List data = serviceRequest.get(List.class, "http://order-service/orderItems?orderId={orderId}", orderId);
            List<OrderItem> items = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                OrderItem orderItem = BeanUtils.mapToModel((Map) data.get(i), OrderItem.class);
                items.add(orderItem);
            }
            return items;
        });
    }
}
